package org.mozhu.mboot.core.web.resource;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.mozhu.mboot.core.config.ApplicationConfiguration;
import org.springframework.http.CacheControl;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;

import java.util.concurrent.TimeUnit;

@Slf4j
public class ExternalWebResourceConfigurer extends BaseWebResourceConfigurer {
    // web.resource 指定上传资源的路径，如http://static.xxx.com
    private static final String PROPERTY_KEY_WEB_RESOURCE_DOMAIN = "web.resource.domain";

    @Override
    public void addResourceHandler(ResourceHandlerRegistry registry) {
        // 加载外部静态资源，文件上传至${resourcePath}，则浏览器能直接访问
        String resourcePath = ApplicationConfiguration.get().getProperty("external.static.resource.path");
        String resourceLocation = ApplicationConfiguration.get().getProperty("external.static.resource.location");
        resourceLocation = makeSureResourcePathEndswithSlash(resourceLocation);
        if (StringUtils.isNotBlank(resourcePath) && StringUtils.isNotBlank(resourceLocation)) {
            log.info("Mapping path[{}] to location[{}] ", resourcePath, resourceLocation);
            registry.addResourceHandler(resourcePath).addResourceLocations(resourceLocation).setCacheControl(CacheControl.maxAge(1, TimeUnit.HOURS).noTransform().cachePublic());
        }

        // 浏览器默认能通过http://$host:$port/$contextPath/resource目录访问上传的资源
        // 使用CDN技术优化后，可以配置web.resource.domain来将路径配置到CDN，加速上传资源的访问

        String webResource = ApplicationConfiguration.get().getProperty(PROPERTY_KEY_WEB_RESOURCE_DOMAIN, "");
        webResource = trimLastSlash(webResource);
        servletContext.setAttribute(PROPERTY_KEY_WEB_RESOURCE_DOMAIN, webResource);
        log.info("Set [{}] to [{}]", PROPERTY_KEY_WEB_RESOURCE_DOMAIN, webResource);
    }

}
